# coding=utf-8
# author:xc
# datetime:2018/8/2 8:59


from . import api
import urllib2
import json
from app import util, redis
from dbConnection.MysqlConn import Mysql
from flask import render_template, request, redirect
from app import util, upload
import sys

reload(sys)
sys.setdefaultencoding('utf8')
APPID = "wx087bed01c194a785"
SECRET = 'e19da6efb5b79d404ef807ea8e113b2c'


@api.route('/api/wechat/get', methods=['POST', 'GET'])
def api_wehcaht_get():
    url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + APPID + "&redirect_uri=http://www.deyiauto.cn&response_type=code&scope=snsapi_base&state=1#wechat_redirect"
    # url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx087bed01c194a785&secret=e19da6efb5b79d404ef807ea8e113b2c"
    requests = urllib2.Request(url)
    response = urllib2.urlopen(requests)
    result = response.read()

    print result
    data = {
        "code": result
    }
    return util.to_json(data)


# 获取access_token()
def get_access_token(code):
    try:
        if redis.get('wechat_access_token') is None:
            access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APPID + "&secret=" + SECRET + "&code=" + code + "&grant_type=authorization_code";
            requests = urllib2.urlopen(access_token_url)
            response = requests.read()
            access_token = json.loads(response)['access_token']
            expires_time = json.loads(response)['expires_in']
            redis.set('wechat_access_token', access_token, ex=expires_time)
            return access_token
        else:
            return redis.get('wechat_access_token')
    except Exception as e:
        print e


# 获取用户userInfo
def get_snsapi_userinfo(access_token,):
    pass
